#include "gudb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

int main() {
    printf("=== GuDB Integration Test ===\n");
    
    // Create a temporary directory for testing
    system("mkdir -p /tmp/gudb_test");
    
    // Test 1: Database creation and connection
    printf("1. Testing database creation...\n");
    gudb* db = gudb_open("/tmp/gudb_test", GU_OPEN_CREATE, "admin", "admin");
    if (!db) {
        printf("❌ Failed to create database\n");
        return 1;
    }
    printf("✅ Database created successfully\n");
    
    // Test 2: Transaction creation
    printf("2. Testing transaction creation...\n");
    gudb_txn* txn = gudb_begin(db, GU_TXN_RC);
    if (!txn) {
        printf("❌ Failed to create transaction\n");
        gudb_close(db);
        return 1;
    }
    printf("✅ Transaction created successfully\n");
    
    // Test 3: SQL parsing and execution - INSERT
    printf("3. Testing INSERT statement...\n");
    result_t* result = NULL;
    int insert_ret = gudb_exec(txn, "INSERT INTO users VALUES ('john', 'John Doe', 25)", NULL, &result);
    if (insert_ret != GU_OK) {
        printf("❌ Failed to execute INSERT: %d\n", insert_ret);
    } else {
        printf("✅ INSERT executed successfully\n");
        gudb_free_result(result);
    }
    
    // Test 4: SQL parsing and execution - SELECT
    printf("4. Testing SELECT statement...\n");
    result = NULL;
    int select_ret = gudb_exec(txn, "SELECT * FROM users", NULL, &result);
    if (select_ret != GU_OK) {
        printf("❌ Failed to execute SELECT: %d\n", select_ret);
    } else {
        printf("✅ SELECT executed successfully\n");
        if (result) {
            printf("   Result: %u rows, %u columns\n", result->row_count, result->col_count);
            if (result->column_names && result->col_count > 0) {
                printf("   Columns: ");
                for (uint32_t i = 0; i < result->col_count; i++) {
                    printf("%s ", result->column_names[i] ? result->column_names[i] : "NULL");
                }
                printf("\n");
            }
            gudb_free_result(result);
        }
    }
    
    // Test 5: Transaction commit
    printf("5. Testing transaction commit...\n");
    int commit_ret = gudb_commit(txn);
    if (commit_ret != GU_OK) {
        printf("❌ Failed to commit transaction: %d\n", commit_ret);
    } else {
        printf("✅ Transaction committed successfully\n");
    }
    
    // Test 6: Database cleanup
    printf("6. Testing database cleanup...\n");
    int close_ret = gudb_close(db);
    if (close_ret != GU_OK) {
        printf("❌ Failed to close database: %d\n", close_ret);
    } else {
        printf("✅ Database closed successfully\n");
    }
    
    printf("\n=== Integration Test Complete ===\n");
    
    // Cleanup test directory
    system("rm -rf /tmp/gudb_test");
    
    return 0;
}